<template>
  <dys-modal
    :open="open"
    :title="t('视图管理')"
    :confirm-loading="loading"
    @cancel="emit('cancel')"
    @ok="handleSubmit"
    :width="1200"
  >
    <template #otherBtn v-if="!!model?.viewId">
      <a-button type="primary" @click="handlePublish">
        <UploadOutlined />{{ t("发布") }}
      </a-button>
    </template>
    <a-row>
      <a-col :span="6">
        <view-info-card
          :validate-infos="validateInfos"
          :model="model"
          :open="open"
        ></view-info-card>
      </a-col>
      <a-col :span="18">
        <view-field-card :model="model"></view-field-card>
      </a-col>
    </a-row>
  </dys-modal>
</template>
<script lang="ts" setup>
import { provide, reactive, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import { Form, message } from "ant-design-vue";
import { add, publish, update } from "@/api/low-code/view";
import type { QueryResult } from "@/api/low-code/view/typing";
import ViewInfoCard from "./view-info-card.vue";
import ViewFieldCard from "./view-content-card.vue";
import type { ViewParams } from "@/api/low-code/view/typing";
import type { FormRule } from "@/typing";
import { MODEL_REF } from "..";
import { pick } from "lodash";
interface Props {
  /**弹窗 */
  open: boolean;
  /**行数据 */
  model: QueryResult;
}
const props = defineProps<Props>();
const emit = defineEmits(["cancel", "ok"]);
const { t } = useI18n();
const loading = ref(false);
const initValue = (): ViewParams => ({
  viewId: null,
  viewName: null,
  viewCode: null,
  viewContent: null,
  viewDesc: null,
  viewStatus: "Y",
});
const modelRef = reactive(initValue());
provide(MODEL_REF, modelRef);
const modelRule = reactive<FormRule<ViewParams>>({
  viewName: [{ required: true, message: () => t("请输入视图名称") }],
  viewCode: [{ required: true, message: () => t("请输入视图编码") }],
});
const { validate, validateInfos, resetFields } = Form.useForm(
  modelRef,
  modelRule
);
/**提交 */
const handleSubmit = async () => {
  try {
    await validate();
  } catch {
    return message.warning(t("校验失败"));
  }
  loading.value = true;
  const { success } = await (props.model?.viewId ? update : add)(modelRef);
  loading.value = false;
  if (success) {
    message.success(props.model?.viewId ? t("修改成功") : t("新增成功"));
    emit("ok");
    emit("cancel");
  }
};
/**发布数据表 */
const handlePublish = async () => {
  loading.value = true;
  const { success } = await publish({ viewId: modelRef.viewId });
  loading.value = false;
  if (success) {
    message.success(t("发布成功"));
    emit("ok");
    emit("cancel");
  }
};
watch(
  [() => props.model, () => props.open],
  ([model]) => {
    resetFields(pick(model || initValue(), Object.keys(modelRef)));
  },
  { immediate: true }
);
</script>
